package com.qiyang.contoller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class FileController {

    /**
     * 基于Servlet API方式下载
     * SpringMVC提供的方式不推荐使用，无法设置缓冲区
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("download")
    public String download(HttpServletRequest request, HttpServletResponse response) {
        String realPath = request.getServletContext().getRealPath("/images/keting.png");

        File file = new File(realPath);

        String fileName = file.getName();

        try {
            /**
             * content-disposition 默认在网页直接打开，设置后以文件下载方式打开
             * attachment 以下载的方式打开文件，设置下载文件名，防乱码
             */
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            FileInputStream fileInputStream = new FileInputStream(realPath);
            int len = 0;
            byte[] buffer = new byte[1024];
            ServletOutputStream outputStream = response.getOutputStream();
            while ((len = fileInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * SpringMVC提供，不支持缓冲区，作为了解，不推荐使用
     *
     * @return
     */
    @RequestMapping("/mvc/download")
    public ResponseEntity<byte[]> mvcDownload() {
        String body = "body";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Set-Cookie", "name=qiyang");
        return new ResponseEntity<byte[]>(body.getBytes(), httpHeaders, HttpStatus.OK);
    }

    /**
     * 基于MultipartFileResolve 文件上传
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/upload")
    public String upload(String desc, MultipartFile file) {
        System.out.println("desc = " + desc);
        System.out.println("file.name = " + file.getOriginalFilename());

        String path = "D:\\java\\" + file.getOriginalFilename();
        try {
            file.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 基于MultipartFileResolve 多文件上传
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/multi/upload")
    public String multiUpload(String desc, MultipartFile[] files) {
        System.out.println("desc = " + desc);

        for (MultipartFile file: files) {
            System.out.println("file.name = " + file.getOriginalFilename());

            String path = "D:\\java\\" + file.getOriginalFilename();
            try {
                file.transferTo(new File(path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "success";
    }

    /**
     * 基于MultipartFileResolve 多文件上传
     * 多线程上传文件
     * @return
     */
    @ResponseBody
    @PostMapping("/multi2/upload")
    public String multi2Upload(String desc, MultipartFile[] files) {

        for (MultipartFile file: files) {
            Thread thread = new Thread(() -> {
                System.out.println("file.name = " + file.getOriginalFilename());
                String path = "D:\\java\\" + file.getOriginalFilename();
                try {
                    file.transferTo(new File(path));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            // 启动线程
            thread.start();
            // 让主线程等待子线程执行完成后，再继续执行
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return "success";
    }
}
